#include "palettequantizer.h"

namespace WingGif {

PaletteQuantizer::PaletteQuantizer(QVector<QColor> palette)
    : Quantizer(true, this) {
  colors = palette;
}

uchar PaletteQuantizer::quantizePixel(QColor pixel) {
  uchar colorIndex = 0;
  auto leastDistance = INT_MAX;

  // Loop through the entire palette, looking for the closest color match.

  auto colortable = colorTable();
  for (auto index = 0; index < colortable.count(); index++) {
    auto paletteColor = colortable[index];

    auto redDistance = paletteColor.red() - pixel.red();
    auto greenDistance = paletteColor.green() - pixel.green();
    auto blueDistance = paletteColor.blue() - pixel.blue();

    auto distance = (redDistance * redDistance) +
                    (greenDistance * greenDistance) +
                    (blueDistance * blueDistance);

    if (distance < leastDistance) {
      colorIndex = uchar(index);
      leastDistance = distance;

      // And if it's an exact match, exit the loop.
      if (0 == distance)
        break;
    }
  }

  return colorIndex;
}

QVector<QColor> PaletteQuantizer::buildPalette() { return colors; }

} // namespace WingGif
